package com.yang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.domain.Bill;
import com.yang.exception.BaseException;
import com.yang.mapper.BillMapper;
import com.yang.mapper.CategoryMapper;
import com.yang.service.BillService;
import com.yang.utils.ThreadLocalUtil;
import com.yang.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BillServiceImpl extends ServiceImpl<BillMapper, Bill> implements BillService {

    @Autowired
    private CategoryMapper categoryMapper;

    private void checkStatus(Integer status){
        if (status!=1&&status!=-1){
            throw new BaseException("请求账单异常,请检查请求路径");
        }
    }

    @Override
    public ResponseResult getBillList(Integer status) {
        checkStatus(status);

        //1.获取用户id
        Long userId = Long.valueOf(ThreadLocalUtil.get().toString());

        //2.根据用户id以及status状态获取帐单列表
        //  构建查询条件
        LambdaQueryWrapper<Bill> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(Bill::getUserId,userId);
        if (status==1){
            //获取收入账单列表
            queryWrapper.isNotNull(Bill::getIncome);
        }else if (status==-1){
            //获取支出账单列表
            queryWrapper.isNotNull(Bill::getExpenditure);
        }

        //3.查询账单列表
        List<Bill> billList = this.list(queryWrapper);
        return ResponseResult.success(billList);
    }

    @Override
    public ResponseResult addBill(Integer status, Bill bill) {
        checkStatus(status);

        bill.setId(null);
        //获取用户id
        Long userId = Long.valueOf(ThreadLocalUtil.get().toString());
        bill.setUserId(userId);

        if (status==1){
            //收入账单，将支出置为空
            bill.setExpenditure(null);
        } else if (status==-1) {
            //支出账单，将收入置为空
            bill.setIncome(null);
        }

        //设置账单分类
        bill.setCategoryName(categoryMapper.selectById(bill.getCategoryId()).getName());

        //添加账单
        this.save(bill);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult deleteBill(Long id) {
        this.removeById(id);
        return ResponseResult.success("删除成功",null);
    }

    @Override
    public ResponseResult updateBill(Bill bill, Integer status) {
        checkStatus(status);
        //获取用户id
        Long userId = Long.valueOf(ThreadLocalUtil.get().toString());
        bill.setUserId(userId);

        if (status==1){
            bill.setExpenditure(null);
        }else if (status==-1){
            bill.setIncome(null);
        }

        //修改账单
        this.updateById(bill);
        return ResponseResult.success("修改成功",null);
    }
}
